<template>
  <div class="lottery_canvas">
    <canvas class='item' ref="wheelcanvas" width='422px' height='422px'></canvas>
    <result-dialog :visible.sync="isShowResult" :type="type"></result-dialog>
  </div>
</template>

<script>
  import base from '../baseurl'
  import ResultDialog from './result_dialog'
  export default {
    name: 'lottery_canvas',
    props: {
      prizes: {
        // type: [Array, Object],
        required: true
      },
      times: {}
    },
    data () {
      return {
        isShowResult: false,
        type: '',
        startColor: '#fedb03',
        endColor: '#fccd02',
        baseurl: base.BASE,
        lotteryDataBuffer: null // 数据暂存
      }
    },
    components: {
      ResultDialog
    },
    computed: {
      turnplate () {
        return {
          background: '#FFBE04',
          prizeList: [], // 大转盘奖品名称
          prizeImg: ['./images/download_icon_18.png'], // 大转盘奖品名称
          colors: [this.startColor, this.endColor, this.startColor, this.endColor, this.startColor, this.endColor], // 大转盘奖品区块对应背景颜色
          outsideRadius: 191, // 大转盘外圆的半径
          textRadius: 152, // 大转盘奖品位置距离圆心的距离
          wordWrapLength: 8,
          insideRadius: 65, // 大转盘内圆的半径
          startAngle: 0,
          initAngle: -50, // 开始角度
          rotating: false, // false:旋转; ture:停止
          requesting: false
        }
      }
    },
    created () {
      if (this.prizes) {
        this.$nextTick(() => {
          this.init()
        })
      }
    },
    watch: {
      'prizes': function () {
        this.$nextTick(() => {
          this.init()
        })
      }
    },
    methods: {
      init () {
        console.log(this.prizes)
        this.turnplate.prizeList = this.prizes
        this.loadPrizeThumb(this.turnplate.prizeList)
      },
      // 预加载图片
      loadPrizeThumb (prizeList, loadedCb) {
        let _imgLoadedCount = 0
        let _this = this
        prizeList.forEach((item, i) => {
          let img = new Image()
          img.src = _this.baseurl + item.thrumb
          console.log(img)
          $(img).on('load', function () {
            _imgLoadedCount++
            prizeList[i].thrumb = img
            // 图片加载完成初始化转盘
            if (_imgLoadedCount === prizeList.length) {
              _this.drawCanvas()
              loadedCb && loadedCb()
            }
          })
        })
      },
      // 画转盘
      drawCanvas () {
        let canvas = this.$refs.wheelcanvas
        let turnplate = this.turnplate
        if (!canvas) return false

        let lineHeight = 18
        // 根据奖品个数计算圆周角度
        let arc = Math.PI * 2 / turnplate.prizeList.length
        let ctx = canvas.getContext('2d')

        // 背景色
        ctx.strokeStyle = turnplate.background

        // font 属性设置或返回画布上文本内容的当前字体属性
        ctx.font = '500 18px/2 Microsoft YaHei'

        /**
         * canvas 绘图默认中3点钟位置开始绘制 需校正角度
         * canvas 绘图使用弧度制
         * 绘制指定角度对应的奖品
         * */
        console.log(turnplate.prizeList)
        for (let i = 0; i < turnplate.prizeList.length; i++) {
          let angle = turnplate.startAngle + i * arc

          // 修正角度
          angle = angle - (Math.PI / 2 + arc / 2)
          ctx.fillStyle = turnplate.colors[i]
          console.log(angle, arc)
          ctx.beginPath()
          ctx.arc(211, 211, turnplate.outsideRadius, angle, angle + arc, false) // arc(x,y,r,起始角,结束角,绘制方向)
          // 方法创建弧/曲线（用于创建圆或部分圆）
          ctx.arc(211, 211, turnplate.insideRadius, angle + arc, angle, true)
          ctx.stroke()
          ctx.fill()

          // 锁画布(为了保存之前的画布状态)
          ctx.save()

          // ----绘制奖品开始----
          ctx.fillStyle = '#b41819'
          let text = turnplate.prizeList[i].shorttitle

          // translate方法重新映射画布上的 (0,0) 位置
          ctx.translate(211 + Math.cos(angle + arc / 2) * turnplate.textRadius, 211 + Math.sin(angle + arc / 2) * turnplate.textRadius)

          // rotate方法旋转当前的绘图
          console.log(angle + arc / 2 + Math.PI / 2)
          ctx.rotate(angle + arc / 2 + Math.PI / 2)

          // 奖品名称长度超过一定范围
          // 在画布上绘制填色的文本。文本的默认颜色是黑色
          // measureText()方法返回包含一个对象，该对象包含以像素计的指定字体宽度
          let _wordLen = turnplate.wordWrapLength
          if (this.getLen(text) > _wordLen) {
            let texts = [text.substring(0, _wordLen), text.substring(_wordLen)]
            for (let j = 0; j < texts.length; j++) {
              ctx.fillText(texts[j], -ctx.measureText(texts[j]).width / 2, j * lineHeight)
            }
          } else {
            ctx.fillText(text, -ctx.measureText(text).width / 2, lineHeight / 2)
          }
          // 绘制奖品配图 优化图片视觉尺寸
          let img = turnplate.prizeList[i].thrumb
          let _imgMax = Math.max(img.height, img.width)
          let _imgAbs = Math.abs(img.height - img.width) / _imgMax
          let imgSize = 60 + 20 * _imgAbs
          ctx.drawImage(img, -imgSize / 2, (lineHeight) + (imgSize - img.height) / 2, img.width * (imgSize / _imgMax), img.height * imgSize / _imgMax)
          ctx.restore()
        }
      },
      // 抽奖
      beginLottery () {
        // 正在转动时返回
        if (this.turnplate.rotating === true) return false
        let _dataBuf = this.lotteryDataBuffer

        // 抽奖次数已用完
        if (_dataBuf != null && _dataBuf.clicknums === 0) {
          // 此处显示次数用完弹框
          this.isShowResult = true
          this.type = 'notimes'
          return false
        }

        // 开始转动时请求数据
        this.turnplate.requesting = true
        this.getLotteryData()
      },
      // 获取抽奖数据
      getLotteryData (cb) {
        let _this = this
        $.get(_this.baseurl + 'lotterynew.php?lid=13&action=join', function (data) {
          cb && cb(data)
          // isLuck 3未领取 1中奖
          let isLuck = Number(data.isLuck)
          if (isLuck === 3) {
            _this.$emit('update:showPrizeDialog', true)
            _this.$emit('update:onePrizeData', data)
          } else if (isLuck === 1) {
            _this.turnplate.requesting = false
            _this.lotteryDataBuffer = data
            _this.rotateFn(data)
          } else {
            console.log('抽奖出错')
          }
        }, 'json')
      },
      // 转动转盘
      rotateFn: function (data) {
        let _data = data
        console.log(_data)
        let angles = _data.angle
        this.$emit('update:times', _data.times)
        this.turnplate.rotating = true
        let _this = this
        console.log(this.$refs.wheelcanvas)
        $(this.$refs.wheelcanvas).rotate({
          angle: 0,
          animateTo: 360 * 5 + (360 - angles),
          duration: 5000,
          callback: function () {
            _this.turnplate.rotating = false
            // 显示中奖弹框
            _this.$emit('update:onePrizeData', _data)
            _this.$emit('update:showPrizeDialog', true)
          }
        })
      },
      getLen (str) {
        let len = 0
        for (let i = 0; i < str.length; i++) {
          if (str.charCodeAt(i) > 127 || str.charCodeAt(i) === 94) {
            len += 2
          } else {
            len++
          }
        }
        return len
      }
    }
  }
</script>

<style lang='less'>

</style>